package com.settlement.system.controller;

import com.settlement.system.csv.CsvExportBuilder;
import com.settlement.system.csv.CsvExportUtil;
import com.settlement.system.common.enums.ReturnStatusEnum;
import com.settlement.system.common.exception.ServiceException;
import com.settlement.system.model.entity.common.TblWpDeliveryUnitPrice;
import com.settlement.system.reply.ObjectDataResponse;
import com.settlement.system.service.IBaseService;
import com.settlement.system.service.ITblWpDeliveryUnitPriceService;
import com.settlement.system.service.csv.DateSpiltCsvDatas;
import com.settlement.system.service.extend.UnitPriceBatchSave;
import com.settlement.system.common.util.common.FasUtil;
import com.settlement.system.common.util.common.RedisUtil;
import com.alibaba.excel.context.AnalysisContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * WP-唯品发货单价 前端控制器
 * @author Ximi
 * @since 2020-10-30
 */

@Slf4j
@Api(tags = "WP-唯品发货单价",description = "WP-唯品发货单价")
@RestController
@RequestMapping("/wp/tblWpDeliveryUnitPrice")
public class TblWpDeliveryUnitPriceController extends MergeApiExcelController<TblWpDeliveryUnitPrice, Map<String, Object>> {

    public static final String BATCH_NUMBER = "acs_wp_delivery_unit_price_batch_number";

    @Value("${system.export-root.path}")
    private String exportRootPath;

    @Resource
    private ITblWpDeliveryUnitPriceService tblWpDeliveryUnitPriceService;

    @Override
    public IBaseService init() {
        return tblWpDeliveryUnitPriceService;
    }

    @Override
    public Class<?> getModelClass() {
        return TblWpDeliveryUnitPrice.class;
    }

    @Override
    protected void setParamsModel(Map<String, Object> model) {
        FasUtil.formatInQueryCondition(model, "shopNo","poSku","poNo","sku");
        //FAS-9775 2、【WP-发货单价】查询条件 SKU、POSKU可同时支持大写和小写的查询
        FasUtil.toUpperCase(model, "poSku","sku");
        super.setParamsModel(model);
    }

    @Override
    protected void setFootModel(Map<String, Object> result, Map<String, Object> model) throws ServiceException {
        result.put("foot", getModelClass());
    }

    @Override
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> params = buildParam(request);
        setParamsModel(params);
        Object fileName = "WP-唯品发货单价";
        String path = exportRootPath + System.currentTimeMillis() + "/";
        CsvExportUtil.createCsv()
                .headClass(getModelClass())
                .fileName(fileName.toString())
                .model(CsvExportBuilder.MULTI_ZIP_MODEL)
                .parentPath(path)
                .csvDatas(new DateSpiltCsvDatas(tblWpDeliveryUnitPriceService, params))
                .export(request,response);
    }

    /**
     * 保存数据
     *
     * @param datas
     * @throws ServiceException
     */
    @Override
    protected void saveData(List<TblWpDeliveryUnitPrice> datas) throws ServiceException {
        if(datas.isEmpty()){
            return;
        }

        long batchNumber = RedisUtil.incr(BATCH_NUMBER, 1);
        long stamp = System.currentTimeMillis();
        for (int index = 0; index < datas.size(); index++) {
            datas.get(index).setBatchNumber(batchNumber + "_" + stamp);
        }

        try {
            UnitPriceBatchSave batchSave =  new UnitPriceBatchSave(tblWpDeliveryUnitPriceService, datas);
            batchSave.save();
            message.set(batchSave.getErrorMessage());
            if(StringUtils.isNotEmpty(message.get())){
                throw new ServiceException(message.get());
            }
            int duplicateNumber = batchSave.getDuplicateNumber().get();
            int saveUpNumber = datas.size() - duplicateNumber;
            if(StringUtils.isEmpty(message.get()) && duplicateNumber > 0){
                message.set("保存"+saveUpNumber+"条，忽略"+duplicateNumber+"条");
            }
        } catch (Exception ex) {
            tblWpDeliveryUnitPriceService.deleteByBatchNumbers(datas.get(0).getBatchNumber(),
                    datas.get(datas.size() - 1).getBatchNumber());

            log.error("保存数据异常",ex);
            throw new ServiceException(ex.getMessage(),ex);
        }
    }

    @Override
    public String verifyImportObject(TblWpDeliveryUnitPrice detail, AnalysisContext analysisContext) {
        if (StringUtils.isBlank(detail.getShopNo())) {
            return "店铺编码不能为空";
        }
        if (StringUtils.isBlank(detail.getPoNo())) {
            return "PO单号不能为空";
        }
        if (StringUtils.isBlank(detail.getSku())) {
            return "SKU不能为空";
        }
        if (StringUtils.isBlank(detail.getPoSku())) {
            return "POSKU不能为空";
        }
        if (detail.getPrice() == null) {
            return "发货单价不能为空";
        }

        return null;
    }

    @ApiOperation("刷新")
    @RequestMapping(value = "refresh", method = {RequestMethod.POST})
    @ResponseBody
    protected ObjectDataResponse refresh(@RequestBody Map<String, Object> model, HttpServletRequest request) {
        try {
            tblWpDeliveryUnitPriceService.refresh();
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_SUCCESS);
        } catch (Exception ex) {
            log.info("刷新数据异常", ex);
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL);
        }
    }
}

